import cookie from "./cookie"
import store from "@/store"

//单次调用函数
function once(fn, context) {
  let isCalled = 0

  var caller = function() {
    let result
    if (!isCalled) {
      result = fn.apply(context || this, arguments)
    }
    return result
  }

  caller.isCalled = isCalled

  return caller
}

/**
 * vw转成px
 *
 * @param {Number} vw
 * @returns {Number}
 */
function vwToPx(vw) {
  const width = window.innerWidth
  return Math.round(width * (0.01 * vw) * 100) / 100
}

//可以遍历对象或者数组，用法参照Array.forEach()
function forEach(obj, callback) {
  if (obj === null || obj === undefined) {
    return
  }

  if (typeof obj === "string") {
    obj = [obj]
  }

  for (let key in obj) {
    if (obj[key] === undefined) {
    }
    // console.log(obj.ke)
    callback.call(window, obj[key], key, obj)
  }
}

/**
 * 循环
 *
 * @param {Function} callback  回调
 * @param {Number} length 循环次数
 */
function loop(callback, length) {
  for (let i = 0; i < length; i++) {
    callback.call(this, i)
  }
}

/**
 * 对象转关联数组
 *
 * @param {Object} obj
 * @returns {Array}
 */
function objectToAssociativeArray(obj) {
  const arr = []
  for (let key in obj) {
    arr["key"] = obj.key
  }
  return arr
}

/**
 * 获取登录地址
 *
 * @returns {String}
 */
function getLoginUrl() {
  return "/user/sign_in?redirect_uri=" + encodeURIComponent(location.href)
}

/**
 * 获取登录地址
 *
 * @returns {String}
 */
function getLoginUrl() {
  return "/user/sign_in?redirect_uri=" + encodeURIComponent(location.href)
}

//获取对象遍历第一个key的value
function pickFirstValue(obj) {
  for (let k in obj) {
    return obj[k]
  }
}

//获取登录cookie信息，并写入vuex
function getLoginData() {
  let json = cookie.getItem("www_user")
  if (json) {
    json = JSON.parse(json)
    store.commit("refreshUserInfo", json)
  }
}

//判断是否为父节点
function isParent(obj, parentObj) {
  while (
    obj != undefined &&
    obj != null &&
    obj.tagName.toUpperCase() != "BODY"
  ) {
    if (obj == parentObj) {
      return true
    }
    obj = obj.parentNode
  }
  return false
}

export {
  once,
  vwToPx,
  redirect,
  forEach,
  loop,
  objectToAssociativeArray,
  getLoginUrl,
  pickFirstValue,
  getLoginData,
  isParent
}
